package com.owen.controller;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.owen.pojo.Fenlei;
import com.owen.pojo.Supplier;
import com.owen.pojo.User;
import com.owen.server.UserServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserServer userServer;

    @RequestMapping(value = "/fileExport")
    public void exportUser(User user, HttpServletResponse response) throws ClassNotFoundException, IOException {
        // 生成excel
        ExcelWriter writer = ExcelUtil.getWriter();
        // 数据库查询
        List<User> users = userServer.findByName(user);
        List<Map<String, Object>> rows = users.stream().map(item -> {
            Map<String, Object> maps = new HashMap<>();
            maps.put("id", item.getId().toString());
            maps.put("username", item.getUsername());
            maps.put("password", item.getPassword());
            maps.put("phone", item.getPhone());
            maps.put("trueName", item.getTrueName());
            maps.put("userLock", item.getUserLock());
            maps.put("createTime", DateUtil.format(item.getCreateTime(),"yyyy-MM-dd"));
            return maps;
        }).collect(Collectors.toList());

        // Title
        int columns = Class.forName("com.owen.pojo.User").getDeclaredFields().length;
        writer.merge(columns - 1, "用户信息");
        // Header
        writer.addHeaderAlias("id", "ID");
        writer.addHeaderAlias("username", "登录名");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("phone", "电话");
        writer.addHeaderAlias("trueName", "姓名");
        writer.addHeaderAlias("userLock", "启用状态");
        writer.addHeaderAlias("createTime", "创建时间");
        // Body
        writer.setColumnWidth(0, 30);
        writer.setColumnWidth(1, 30);
        writer.setColumnWidth(2, 30);
        writer.setColumnWidth(3, 30);
        writer.setColumnWidth(4, 30);
        writer.setColumnWidth(5, 30);
        writer.setColumnWidth(6, 30);
        writer.write(rows, true);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode("用户信息-" + DateUtil.today() + ".xls", "utf-8"));
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

    @ResponseBody
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
    public String deleteBatch(Integer [] ids) {
        Map<String,Object> res = new HashMap<>();
        Integer count = userServer.deleteBatch(ids);
        if (count > 0) {
            res.put("code", 200);
            res.put("msg", "删除成功！");
        }else {
            res.put("code", 201);
            res.put("msg", "删除失败！");
        }
        String json = JSON.toJSONString(res);
        return json;
    }

    @RequestMapping(value = "/initName")
    public String initName(HttpSession session) {
        User user = (User) session.getAttribute("login");
        Map<String, Object> res = new HashMap<>();
        if (Optional.ofNullable(user).isPresent()) {
            res.put("code", "200");
            res.put("msg", "已登陆");
            res.put("data", user);
        } else {
            res.put("code", "201");
            res.put("msg", "登陆已超时");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @RequestMapping(value = "/zhuce")
    public String zhuce(User user) {
        Integer integer = userServer.addUser(user);
        Map<String, Object> res = new HashMap<>();
        if (integer > 0) {
            res.put("code", "200");
            res.put("msg", "注册成功");
        } else {
            res.put("code", "201");
            res.put("msg", "注册失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @RequestMapping(value = "disable/{id}", method = RequestMethod.GET)
    public String disable(@PathVariable("id") Integer id){
        Integer integer = userServer.disable(id);
        Map<String, Object> res = new HashMap<>();
        if (integer > 0) {
            res.put("code", "200");
            res.put("msg", "禁用成功");
        } else {
            res.put("code", "201");
            res.put("msg", "禁用失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @RequestMapping(value = "enable/{id}", method = RequestMethod.GET)
    public String enable(@PathVariable("id") Integer id){
        Integer integer = userServer.enable(id);
        Map<String, Object> res = new HashMap<>();
        if (integer > 0) {
            res.put("code", "200");
            res.put("msg", "禁用成功");
        } else {
            res.put("code", "201");
            res.put("msg", "禁用失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @RequestMapping(value = "/find")
    public String find() {

        PageHelper.startPage(1, 10);
        List<User> users = userServer.find();
        PageInfo<User> userInfo = new PageInfo<>(users);

        Map<String, Object> res = new HashMap<>();
        if (Optional.ofNullable(users).isPresent()) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", userInfo);
        } else {
            res.put("code", "201");
            res.put("msg", "未找到用户");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @RequestMapping(value = "/userDelete/{id}", method = RequestMethod.DELETE)
    public String userDelete(@PathVariable("id") Integer id) {
        Integer integer = userServer.userDelete(id);
        Map<String, Object> res = new HashMap<>();
        if (integer > 0) {
            res.put("code", "200");
            res.put("msg", "删除成功");
        } else {
            res.put("code", "201");
            res.put("msg", "删除失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @ResponseBody
    @RequestMapping(value = "/updatepassword", method = RequestMethod.GET)
    public String updatepassword(String password1, String password2, String password3,HttpSession session) {
        User login = (User) session.getAttribute("login");
        Map<String, Object> res = new HashMap<>();
        Integer updatepassword = 0;
        if(!login.getPassword().equals(password1)){
            res.put("code", "201");
            res.put("msg", "旧错误");
        } else if(!password2.equals(password3)) {
            res.put("code", "201");
            res.put("msg", "确认密码");
        } else if(password2.equals(password3)) {
            User user = new User();
            user.setId(login.getId());
            user.setPassword(password2);
            updatepassword = userServer.updatepassword(user);
        }
        if (updatepassword > 0) {
            res.put("code", "200");
            res.put("msg", "修改成功");
        } else {
            res.put("code", "201");
            res.put("msg", "修改失败");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

    @ResponseBody
    @RequestMapping(value = "/findByName", method = RequestMethod.GET)
    public String findByName(User user, Integer xuanzhepage, String currentPage) {

        // 获取页数
        Integer current = 1;
        if (currentPage != null) {
            current = Integer.valueOf(currentPage);
        }

        PageHelper.startPage(current, xuanzhepage);
        List<User> users = userServer.findByName(user);
        PageInfo<User> userInfo = new PageInfo<>(users);

        Map<String, Object> res = new HashMap<>();
        if (Optional.ofNullable(users).isPresent()) {
            res.put("code", "200");
            res.put("msg", "查询成功");
            res.put("data", userInfo);
        } else {
            res.put("code", "201");
            res.put("msg", "未找到用户");
        }
        String s = JSON.toJSONString(res);
        return s;
    }

}